import { useNavigate } from "react-router-dom";
import { Button, Checkbox, Col, Form, Input, message, Row } from "antd"
import 'antd/dist/antd.min.css'
import axios from "axios";
import { useRef, useState } from "react";
import '../../scss/use/register.scss';


function Register() {
  //获取输入的电话号码
  const [phone, setPhone] = useState<string>('');
  //
  const [counting, setCounting] = useState<any>(false);
  const [count, setCount] = useState<any>(60);

  //路由重定向
  const navigate = useNavigate();
  function ToLogin() {
    navigate({ pathname: '/login' })
  }
  const formRef = useRef<any>();
  const [form] = Form.useForm();
  //保存后端返回的验证码信息
  const [code, setCode] = useState<string>('');

  //获取验证码
  //判断手机号是否输入
  const getCheckCode = (event: any) => {
    console.log(phone)
    if (phone) {
      axios.defaults.withCredentials = true
      axios.get('http://localhost:81/send', {
        params: { phone }
      }).then((res: any) => {
        console.log(res);
        setCode(res.data.check)
      }).catch(function (error: any) {
        console.log(error);
      });
      message.success('验证码发送成功')
      // 将发送验证码改为倒计时，并将按钮设置为禁用
      // setCaptcha1(count)
      setCounting(true)
      let num=60
      setInterval(() => {
        if (num <= 0) {
          setCounting(false)
        }else{
          setCount(num)
          num--
        }
      }, 1000)
      console.log(num)
    } else {
      message.error('请输入手机号')
    }
  }




  //注册
  const onFinish = (values: any) => {
    // console.log('Received values of form: ', values);
    axios.defaults.withCredentials = true
    //注册
    axios.post('http://localhost:81/regLogin', {
      params: { values }
    }).then((res: any) => {
      console.log(res);
      if (res.data.code === 0) {
        message.error(res.data.msg);
      } else if (res.data.code === -1) {
        message.error(res.data.msg);
      } else if (res.data.code === 2) {
        message.error(res.data.msg);
      } else {
        //注册成功
        message.success(res.data.msg);
        ToLogin();
        // alert(res.data.msg)
      }
    }).catch(function (error: any) {
      console.log(error);
    });
  };

  return (

    <div className="cover">
      <div className="register">
        <div className="title">
          <span>加入我们</span>
          <span className="log">7MX</span>
        </div>
        <div className="detail">
          Best Art Photography Community
        </div>
        {/* 表单 */}
        <Form
          name="register"
          onFinish={onFinish}
          scrollToFirstError
        >
          <Form.Item
            name="phone"
            rules={[{ required: true, message: '请输入手机号', max: 11 },
            ({ getFieldValue }) => ({
              validator(_, e: any) {
                const value = getFieldValue('phone');
                if (value) {
                  if (value.length === 11 && !(/^(1[3456789]|9[28])\d{9}$/).test(value)) {
                    return Promise.reject(new Error('请输入11位有效电话号码!'));
                  }
                  if (value.length !== 11) {
                    return Promise.reject(new Error('请输入11位电话号码!'));
                  }
                  return Promise.resolve();
                }
                return Promise.resolve();
              },
            }),
            ]}
          >
            <Input onChange={(e) => { setPhone(e.target.value) }} style={{ width: '100%' }} size='large' placeholder="请输入手机号" name="tele" />
          </Form.Item>

          <Form.Item>
            <Row gutter={8}>
              <Col span={12}>
                <Form.Item
                  name="captcha"
                  dependencies={['phone']}
                  hasFeedback
                  noStyle
                  rules={[{ required: true, message: '请输入验证码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      //如果输入的验证码不等于保存的验证码，提示请输入正确的验证码!
                      if (code == value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('请输入正确的验证码!'));
                    },
                  }),
                  ]}
                >
                  <Input size='large' placeholder="请输入验证码" maxLength={6} onChange={(e) => { setCode(e.target.value) }} />
                </Form.Item>
              </Col>
              <Col>
                <Button
                  size='large'
                  onClick={getCheckCode}
                  disabled={counting}
                >{counting ? `${count}秒后重发` : '获取验证码'}</Button>
              </Col>
            </Row>
          </Form.Item>


          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: '请输入你的密码',
              },
            ]}
            hasFeedback
          >
            <Input.Password size='large' placeholder="请输入密码" maxLength={8} minLength={4} />
          </Form.Item>

          <Form.Item
            name="confirm"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请再次确认你的密码',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve(console.log(getFieldValue('password')));
                  }
                  return Promise.reject(new Error('请输入两次相同的密码!'));
                },
              }),
            ]}
          >
            <Input.Password size='large' placeholder="请再次输入密码" />
          </Form.Item>

          <Form.Item
            name="agreement"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('你必须同意协议')),
              },
            ]}
          >
            <Checkbox>
              同意 <a href="https://static.7mx.com/static/pdf/7mx.pdf">《平台服务条款》</a><a href="https://static.7mx.com/static/pdf/xy.pdf">《用户协议》</a>
            </Checkbox>
          </Form.Item>

          <span>注册即代表你已经认真阅读并同意接受</span>

          <Form.Item>
            <Button type="primary" htmlType="submit" block size='large' style={{ width: '400px' }}>
              注册
            </Button>
          </Form.Item>

          <a href="#" onClick={ToLogin}>已有账号? 立即登录</a>
        </Form>
      </div>
    </div>
  )
}

export default Register